// pages/manydays/manydays.js
const app = getApp()
const $req = require('../../utils/req.js') //接口封装文件
Page({
  /**
   * 页面的初始数据
   */
  data: {
    dateMask:true,
    selectTimes: new Date().toISOString().substring(0, 10),
    endTimes: new Date().toISOString().substring(0, 10),
    marquee:{
      type:Boolean,
    },
    scheduleLegend: [{
      name: '可预订',
      color: '#D1D1D1',
    }, {
      name: '不可预订',
      color: '#777575'
    }, {
      name: '已预订',
      color: '#EA5826',
    }, {
      name: '已选中',
      color: '#FDB644',
    }],
    goodsList: [],
    goodsListTotalPrice: '0.00',
    disAmount: '0',
    date:new Date().toISOString().substring(0, 10),
    selectDays:null,
    datalist:[],
    timelist:[],
    RoomID:null,
    timeInterval: [0,0, 0],//选中日期和选中间距
    roomInfo:[],
    oklist:[],//多日选择 选择详情
    domoney:0,
    totalPrice:0,
    timelists:[],
    Descr:null,
    fileok:[],
    userHead:[],
    user:[],
    myval:null,
    timelenght:0,
    onifrules:false,
    onword:''
  },
 getDate(datestr) {
  var temp = datestr.split("-");
  var date = new Date(temp[0], temp[1] - 1, temp[2]);
  return date;
},
//获得2天时间的间隔的列表
gettimelist(start,end){
  let that = this
  let RoomID = that.data.RoomID
  wx.request({
    url: 'https://www.yulonging.com/dwweb/wxapi.ashx',
    data: {
     //请求后台的分页数据
     cmd:'GetRoomTimesInfoMul',
     RoomID:RoomID,
     Mdate:start,
     MdateTo:end,
    },
    method: "get",
    success(res) {
      let timelists = res.data.DATA.DateList
      let data = []
      console.log(timelists)
      timelists.forEach((item, index) => {
        item.TimeList.forEach((items, indexs) => {
          items.timePoint = items.FromTo.split("-")[0]
           if(items.IsOrder){
               items.CanOrder=true
            }
        })
        data.push({
          daytime:item.MeetDate,
          times:item.TimeList,
          dayindex:index,
      
        })
      })
      console.log(data)
      that.setData({
      timelist:data,
      timelenght:0,
      totalPrice:0,
      domoney:0,
    })
    }
  });
},
add0(m){return m<10?'0'+m:m },
format(shijianchuo)
{
  let that = this
//shijianchuo是整数，否则要parseInt转换
var time = new Date(shijianchuo);
var y = time.getFullYear();
var m = time.getMonth()+1;
var d = time.getDate();
var h = time.getHours();
var mm = time.getMinutes();
var s = time.getSeconds();
return y+'-'+that.add0(m)+'-'+that.add0(d);
},

//获得商品列表
getGoodsList(RoomID) {
  let _this = this
  let data = {
    RoomID: RoomID,
  }
  $req.getGoodsList(data).then(res => {
    let result = res.DATA
    result.forEach((item, index) => {
      item.num = 0
      item.Price = item.Price.toFixed(2)
      item.totalPrice = (item.Price * item.num).toFixed(2)
    })
    _this.setData({
      goodsList: res.DATA
    })
  })
},

checkboxChange(e){
  console.log('checkbox发生change事件，携带value值为：', e.detail.value)
  let that = this;
  let myval=that.data.myval;
  if(typeof(e.detail.value[0])=='undefined'){
    that.setData({
      myval:null
    })
  }else{
    that.setData({
      myval:'y'
    })
  }
  console.log(myval);
},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   let that = this
   let date = new Date().toISOString().substring(0, 10)
   let userInfo = wx.getStorageSync('userInfo')
   let token = wx.getStorageSync('token')
   that.setData({
    RoomID:options.id
   })
  //  that.getRoomTimesInfo(options.id, date)
   that.getGoodsList(options.id)//获取初始化的商品
   let starttime =  that.data.selectTimes
   let endstime =  that.data.endTimes
   that.gettimelist(starttime,endstime)
   //获取当前会议室的详细信息
   that.getRoomInfo(options.id)
   wx.request({
    url: 'https://www.yulonging.com/dwweb/wxapi.ashx?cmd=saveorder',
    data: {
      cmd: 'GetRoomDiscount',
      token: token,
      RoomID: options.id
    },
    method: "get",
    header: {
      'content-type': 'application/json' // 默认值
    },
    success (res) {
      if(res.data.STATUS=='Error'){
        wx.navigateTo({
          url: '../login/login',
        })
      }  
      that.setData({
        disAmount:res.data.DATA.Discount
      })
    }
  })
    wx.request({
      url: 'https://www.yulonging.com/dwweb/wxapi.ashx',
      data: {
        cmd: 'aboutme',
        token:token
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success (data) {
        console.log(data.data.DATA)
        that.setData({
          onword:data.data.DATA.RentDoc
        })
      }
    });
  },
// 规则查看
  onifrulesopen(e){
    let that = this;
    that.setData({
      onifrules:true
    })
  },

  onifrulesout(e){
    let that = this;
    that.setData({
      onifrules:false
    })
  },
  //会议室详情
  getRoomInfo(RoomID) {
    let _this = this
    let data = {
      RoomID: RoomID
    }
    $req.getRoomInfo(data).then(res => {
      console.log(res.DATA)
      _this.setData({
        roomInfo: res.DATA,
        // disAmount:res.DATA.disAmount
      })
    })
  },


  //返回上一页
  navigateBack() {
    wx.navigateBack({
      delta: 1
    })
  },
      // 拨打电话
      ontel(e){
        let that = this
        let  token=  wx.getStorageSync('token')
        wx.request({
          url: 'https://www.yulonging.com/dwweb/wxapi.ashx',
          data: {
            cmd: 'aboutme',
            token:token
          },
          header: {
            'content-type': 'application/json' // 默认值
          },
          success (data) {
            console.log(data.data.DATA)
            wx.makePhoneCall({
              phoneNumber: data.data.DATA.Mobile,
            })
          }
        });
      },
  onword(e){
    // 根据小程序官方API提供
      var that = this;
      var filePath = e.currentTarget.dataset.url;//对应的网络路径，可以是内网的或者外网
      var fileType = e.currentTarget.dataset.type; 
      wx.downloadFile({//下载对应文件
        url: filePath,
        success: function (res) {    
          var filePath = res.tempFilePath;//文件路径    
          wx.openDocument({
            filePath: filePath,   // 装载对应文件的路径
            fileType: fileType,   // 指定打开的文件类型
            showMenu: true,       // 右上角的菜单转发分享操作
            success: function (res) {
              console.log("打开成功");
            },
            fail: function (res) {
              console.log(res);
            }
          })   
        },
        fail: function (res) {
          console.log(res);
        }
      })       
  
    },   
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**日期全选**/
  checkall(e){
    console.log(2222);
    console.log(e);
  },
 //打开时间选择器
 openDateMask(e){
  let _this = this
  _this.setData({
    dateMask:false,
    marquee:true
  })
},
endDateMask(e){
  let _this = this
  _this.setData({
    dateMask:false,
    marquee:false
  })
},
//关闭时间选择器
onSearchInputEvent(e){
  let that = this;
  let value = e.detail.dateMask;
  console.log(value);
    that.setData({
      dateMask:value
    })
   
},


onSearchEvent(e){
  let that = this;
  let select = e.detail.selectDays;
  let value = e.detail.clreashuju.dateMask; 
  let arrendTimes=that.data.endTimes;

    that.setData({
      selectTimes:select,
      dateMask:value
    })
  
  let starttime =  that.data.selectTimes
  let endstime =  that.data.endTimes
   that.gettimelist(starttime,endstime)

},
onEndEvent(e){
  let that = this;
  let select = e.detail.selectDays;
  let value = e.detail.clreashuju.dateMask; 
  let arrselectT=that.data.selectTimes; 
    that.setData({
      endTimes:select,
      dateMask:value
    })
  let starttime =  that.data.selectTimes
  let endstime =  that.data.endTimes
   that.gettimelist(starttime,endstime)
},

 // 计算总金额
 totalPrice() {
  let _this = this
  let roomTiemsCopy = Object.create(_this.data.roomTimes)
  let totalPrice = 0
  let timelenght = _this.data.timelenght

  roomTiemsCopy.forEach((item, index) => {
    if (item.checkFlag) {

      totalPrice += item.Price
    }
  })



  _this.setData({
    totalPrice: (totalPrice).toFixed(2),
    disAmount: (totalPrice*_this.data.dis).toFixed(2)*1,
  })
},

changeGoodsNum(e) {
  let _this = this
  let data = e.currentTarget.dataset
  let goodsList = _this.data.goodsList
  let goods = goodsList[data.index]
  switch (data.type) {
    case "+":
      goods.num += 1
      break
    case "-":
      goods.num -= 1
      break
  }
  if (goods.num < 0) {
    goods.num = 0
  }
  goods.totalPrice = (goods.num * goods.Price).toFixed(2)
  _this.goodsListTotalPrice()
  _this.finsTotalprice()
  _this.setData({
    goodsList: goodsList,
  })
  console.log(goodsList)
},

finsTotalprice() {
  let _this = this
  _this.setData({
    finsTotalprice: (parseFloat(_this.data.disAmount) + parseFloat(_this.data.goodsListTotalPrice)).toFixed(2),
  })
},

goodsListTotalPrice() {
  let _this = this
  let goodsListTotalPrice = 0
  let goodsList = _this.data.goodsList
  goodsList.forEach((item, index) => {
    goodsListTotalPrice += parseFloat(item.totalPrice)
  })
  _this.setData({
    goodsListTotalPrice: goodsListTotalPrice.toFixed(2)
  })
},


touchTimesTables(e){
  let that = this
  let roomInfo = that.data.roomInfo
  let catindex = e.currentTarget.dataset.index //用户点击的时间索引
  let list = e.currentTarget.dataset.list //用户点击的时间索引
  let times = e.currentTarget.dataset.times //用户点击的时间索引
  let timeInterval = that.data.timeInterval//选中日期和选中长度
  let typeValue = roomInfo.SortNm == "大型会议室" ? 7 : 3 //长度 大型会议室8个 小的4个选中
  let oklist = that.data.oklist
  let fileok = that.data.fileok
  //获取全部数据
  let timelist = that.data.timelist
  //获取30天数据
  let daytimelist = timelist[list].times
  //获取点击时间段数据
  let timeinfo = daytimelist[catindex]
  //判断是不是取消点击
  if(timeinfo.IsOrder==true){
    wx.showToast({
      title:'当日时间已被选择',
      icon: 'error',
      duration: 2000
    })
  }else{
    //可以选择
    if ((catindex + typeValue) > daytimelist.length - 1) {
      // 判断点击点位是否超过可选  如果是第一次点击提示  第二次点击选中
      if(timeInterval[0]==0){
        wx.showToast({
          title:'不足最低订购时间',
          icon: 'error',
          duration: 2000
        })
      }else{
      //判断是不是取消 如果不是取消就是新增  
        if(catindex<= oklist[list].index[2] && catindex>=oklist[list].index[1]){
            console.log('时间不足的地方点击取消')
            oklist[list]= {list:list,date:times,index:[0,oklist[list].index[1],oklist[list].index[2]]}
            that.setData({
              oklist:oklist
            })
          daytimelist.forEach((item, index) => {
            if (index >= oklist[list].index[1] && index <=oklist[list].index[2] ) {
                         item.checkFlag = false
              }
          })
          timelist[list].times = daytimelist
          that.setData({
            timelist:timelist,
          })
        }else{
          if(catindex<timeInterval[1]){
            timeInterval[1] =  catindex
            timeInterval[2] = oklist[list].index[2]
          }else if(catindex>timeInterval[2]){
            timeInterval[1] =  oklist[list].index[1]
            timeInterval[2] =  catindex
          }
          console.log('时间不足的地方二次点击')
          oklist[list]= {list:list,date:times,index:[times,timeInterval[1],timeInterval[2]]}
          that.setData({
            oklist:oklist
          })
          daytimelist.forEach((item, index) => {
            if (index >=  timeInterval[1] && index <= timeInterval[2] ) {
                         item.checkFlag = true
              }
          })
          timelist[list].times = daytimelist
          that.setData({
            timelist:timelist,
          })
        }
      }
    }else{
        //判断是不是同一日二次选中
        //if(times==timeInterval[0]){
          if(oklist[list]!=null){
              if(oklist[list].index[0]==0){//判断是不是 删除后重新选择的
                timeInterval[0] = times
                timeInterval[1] =  catindex
                timeInterval[2] =  catindex+ typeValue
                console.log('新的时间点击')
                oklist[list]= {list:list,date:times,index:[times,catindex,catindex+ typeValue]}
                console.log(oklist)
                that.setData({
                  oklist:oklist
                })
                daytimelist.forEach((item, index) => {
                  if (index >= catindex && index <=catindex+ typeValue ) {
                               item.checkFlag = true
                    }
                })
                timelist[list].times = daytimelist
                that.setData({
                  timelist:timelist,
                  timeInterval:timeInterval
                })
              }else{
                //数据并没有被删除进行 二次点击和取消操作
                timeInterval[0] = times
                if(catindex<oklist[list].index[1] || catindex>oklist[list].index[2]){//判断是不是取消 不是取消就是点击放大
                    //详细判断是点击大还是小
                  if(catindex<timeInterval[1]){
                    timeInterval[1] =  catindex
                    timeInterval[2] =  oklist[list].index[2]
                  }else if(catindex>timeInterval[2]){
                    timeInterval[1] =  oklist[list].index[1]
                    timeInterval[2] =  catindex
                  }
                  console.log('二次点击')
                  oklist[list]= {list:list,date:times,index:[times,timeInterval[1],timeInterval[2]]}
                  that.setData({
                    oklist:oklist
                  })
                  daytimelist.forEach((item, index) => {
                    if (index >= timeInterval[1] && index <=timeInterval[2] ) {
                                 item.checkFlag = true
                      }
                  })
                  timelist[list].times = daytimelist
                          that.setData({
                            timelist:timelist,
                            timeInterval:timeInterval
                          })
                }else{
                      //取消点击
                      console.log('取消点击')
                      oklist[list]= {list:list,date:times,index:[0,oklist[list].index[1],oklist[list].index[2]]}
                      that.setData({
                        oklist:oklist
                      })
                      daytimelist.forEach((item, index) => {
                        if (index >= oklist[list].index[1] && index <=oklist[list].index[2] ) {
                                     item.checkFlag = false
                          }
                      })
                      timelist[list].times = daytimelist
                              that.setData({
                                timelist:timelist,
                                //timeInterval:timeInterval
                              })
                    }
                  }
        }else{
          //不是同一日 新的时间 
          timeInterval[0] = times
          timeInterval[1] =  catindex
          timeInterval[2] =  catindex+ typeValue
          console.log('新的时间点击')
          oklist[list]= {list:list,date:times,index:[times,catindex,catindex+ typeValue]}
          console.log(oklist)
          that.setData({
            oklist:oklist
          })
          daytimelist.forEach((item, index) => {
            if (index >= catindex && index <=catindex+ typeValue ) {
                         item.checkFlag = true
              }
          })
          timelist[list].times = daytimelist
                  that.setData({
                    timelist:timelist,
                    timeInterval:timeInterval
                  })
        }
    }
  }
  that.getmoneylist()
},
//计算金额加上折扣
getmoneylist(e){
  let that = this
  let timelist = that.data.timelist
  //根据预定的选中进行金额计算
  let oklist = that.data.oklist
  let listinfo = []
  oklist.forEach((item, index) => {
    if(item.index.times!=0){
      listinfo[index] = timelist[index].times
    }  
  })
  let nolist = []
  listinfo.forEach((item, index) => {
    item.forEach((itmes,indexs)=>{
      nolist.push(itmes)
    })
  })
  let totalPrice = 0
  let timelenghts = []
  let Price = 0
  nolist.forEach((item,index)=>{
    if (item.checkFlag) {
      console.log(item.Price)
      Price = item.Price*1
      totalPrice += item.Price*1
      timelenghts.push({item})
    }
  })
    let timelenght = timelenghts.length*1/2
    //优惠
    if(timelenght>8){
      totalPrice = totalPrice-Price*2
      // if(totalPrice<4000){
      //   totalPrice = 4000
      // }
      if(totalPrice<Price*2*8){
        totalPrice = Price*2*8
      }
    }
  that.setData({
    timelenght:timelenghts.length*1/2,
    totalPrice: (totalPrice).toFixed(2),
    domoney: (totalPrice*that.data.disAmount).toFixed(2)*1,
  })

},
getseiz(e){
console.log(e)
  let that = this
  that.setData({
    Descr:e.detail.value
  })
},
subok(e){
  //提交表单
  let that = this
  let Descr = that.data.Descr?that.data.Descr:''
  let goodsList = that.data.goodsList
  let oklist = that.data.oklist
  let timelist = that.data.timelist
  let RoomID = that.data.RoomID
  let starttime =  that.data.selectTimes
  let endstime =  that.data.endTimes
  var Nums = []
  let Goods = []
  let Details= []
  //获取订单ID
  let listinfo = []
  let myval = that.data.myval
  if(myval==null){
    wx.showToast({
      title: '请阅读预订须知',
      icon: 'error',
      duration: 2000
    })
  }else{
  oklist.forEach((item, index) => {
    if(item.index.times!=0){
      listinfo[index] = timelist[index].times
    }
  })

  listinfo.forEach((item, index) => {
    var TimesID = []
    var Mdates = []
    item.forEach((items, indexs) => {
      if (items.checkFlag) {
        TimesID+= items.TimesID+','
        Mdates = oklist[index].date
      }
    })
    Details.push({
      Mdate: Mdates,
      TimesID: TimesID,
    });
  })
  console.log(Details)
  //商品
  goodsList.forEach((item, index) => {
    if(item.num!=0){
      Goods.push({
        GoodsID: item.GoodsID,
        Nums: item.num
      })
    }
  })
  let data = {
    Token: wx.getStorageSync("token") ? wx.getStorageSync("token") : '',
    OrderNo: '', //	string	订单编号(新订单为空)
    RoomID: RoomID,
    Mdate: starttime, //date	会议室预订日期(开始日期）
    MdateTo: endstime, //	date	会议室预订日期(结束日期）
    Descr: Descr, //	string	订单备注
    Details: Details, //	Json	列表
    Goods: Goods, // Goods 商品
    MeetName:'',
  }
  var jsonObj = JSON.stringify(data);

  wx.request({
    url: 'https://www.yulonging.com/dwweb/wxapi.ashx?cmd=saveorder',
    data: jsonObj,
    method: "post",
    success(res) {
      console.log(res)
        if(res.data.STATUS=='Success'){
        wx.navigateTo({
          url: '/pages/orderInfo/orderinfodetail?OrderNo='+res.data.DATA.OrderNo+'&TotalFee='+res.data.DATA.TotalFee,
        })
        }else{
          wx.showToast({
            title: '当前时间已被订购',
            icon: 'error',
            duration: 2000
          })
        setTimeout(function () {
          //刷新时间选择列表
          that.getGoodsList(RoomID)
          that.gettimelist(starttime,endstime)
          that.setData({
            oklist:[]
          })
        }, 2000) //延迟时间
        }
    }
 })
}
}
})